package com.gec.web;

import com.gec.domain.Dept;
import com.gec.domain.Employee;
import com.gec.domain.Job;
import com.gec.service.EmployeeService;
import com.gec.service.impl.EmployeeServletImpl;
import com.gec.utils.CrossRegion;
import com.gec.utils.PageModel;
import com.gec.utils.Tool;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = {"/findAllemployees","/addEmployee","/deleteEmployee","/findEmployeeById","/updateEmployee"})
public class EmployeeController extends HttpServlet {

    //service对象
    EmployeeService service=new EmployeeServletImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //跨域设置
        CrossRegion.setCross(response);

        if("OPTIONS".equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        //请求的servlet路径
        String servletPath = request.getServletPath();

        //路径
        if(servletPath.equals("/findAllemployees")){
            findAllemployees(request,response);
        }else if(servletPath.equals("/addEmployee") || servletPath.equals("/updateEmployee")){
            empAddUpdata(request,response);
        }else if(servletPath.equals("/deleteEmployee")){
            deleteemployee(request,response);
        }else if(servletPath.equals("/findEmployeeById")){
            findByTdemployee(request,response);
        }
    }

    /**
     * 根据id查询
     * */
    private void findByTdemployee(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        Employee employees=service.findById(Integer.parseInt(id));
        System.out.println("employees:"+employees);

        Map<String,Object>map=new HashMap<>();
        map.put("code",200);
        map.put("employees",employees);

        Gson gson=new Gson();
        String json = gson.toJson(map);

        response.getWriter().write(json);
    }

    /**
     * 删除
     * */
    private void deleteemployee(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        service.deleteEmployee(Integer.parseInt(id));
        Map<String,Object>map=new HashMap<>();
        map.put("code",200);
        map.put("message","success");

        Gson gson=new Gson();
        String json = gson.toJson(map);

        response.getWriter().write(json);
    }

    /**
     * 添加和修改
     * */
    private void empAddUpdata(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取参数
        Tool.printAllRequestParameter(request);

        String id = request.getParameter("id");
        Employee employee=new Employee();
        employee.setName(request.getParameter("name"));
        employee.setCARD_ID(request.getParameter("card_id"));
        employee.setAddress(request.getParameter("address"));

        String birthday = request.getParameter("birthday");
        //先判断生日是否为空
        if(!"".equals(birthday)) {
            Date date;
            //先创建一个时间类,
            //实现将字符串转成日期类型
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            try {
                date = simpleDateFormat.parse(birthday);
                System.out.println("date:" + date);
                System.out.println(date.getTime());

                employee.setBirthday(date);
            } catch (ParseException e) {
                date=null;
            }
        }


        employee.setPhone(request.getParameter("phone"));
        employee.setQQ_NUM(request.getParameter("QQ_NUM"));
        employee.setEmail(request.getParameter("email"));
        employee.setParty(request.getParameter("party"));
        employee.setTel(request.getParameter("tel"));
        employee.setPOST_CODE(request.getParameter("post_code"));
        employee.setRace(request.getParameter("race"));
        employee.setEducation(request.getParameter("education"));
        employee.setSpeciality(request.getParameter("speciality"));
        employee.setHobby(request.getParameter("hobby"));
        String sex = request.getParameter("sex");
        if(sex !=null && !"".equals(sex)){
            employee.setSex(Integer.parseInt(sex));
        }

        String dept_id = request.getParameter("dept_id");
        System.out.println("dept_id = " + dept_id);
        //因为基本数据类型不能为0/空字符，需要转换一下
        Dept dept = new Dept();
        if(dept_id !=null && !"".equals(dept_id)){
            dept.setId(Integer.parseInt(dept_id));
        }
        employee.setDept(dept);

        String job_id = request.getParameter("job_id");
        //因为基本数据类型不能为0/空字符，需要转换一下
        Job job = new Job();
        if(job_id !=null && !"".equals(job_id)){
            job.setId(Integer.parseInt(job_id));
        }
        employee.setJob(job);

        employee.setId(Integer.parseInt(id));
        //如果传来的id是0则为添加，否则修改
        if(id.equals("0")){
            service.addEmployee(employee);
        }else{
            service.updateEmployee(employee);
        }

        Map<String,Object>map=new HashMap<>();
        map.put("code",200);
        map.put("message","success");
        Gson gson=new Gson();
        String json = gson.toJson(map);
        response.getWriter().write(json);
    }

    /**
     * 查询全部
     * @param request
     * @param response
     */
    private void findAllemployees(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String pageIndex=request.getParameter("pageIndex");
        int page=!"".equals(pageIndex) && pageIndex !=null ? Integer.parseInt(pageIndex) : 1;
        PageModel model=new PageModel();
        model.setPageIndex(page);

        List<Employee> employees=null;

        String name = request.getParameter("name");
        String card_id = request.getParameter("CARD_ID");
        String phone = request.getParameter("phone");
        String sex = request.getParameter("sex");
        String dept_id = request.getParameter("dept_id");
        String job_id = request.getParameter("job_id");

        Employee employee=new Employee();

        //判断姓名是否为空
        if (name != null && !"".equals(name)) {
            //System.out.println("name = " + name);
            employee.setName(name);
        }
        //判断手机是否为空
        if (phone != null && !"".equals(phone)) {
            System.out.println("phone = " + phone);
            employee.setPhone(phone);
        }
        //判断身份证是否为空
        if (card_id != null && !"".equals(card_id)) {
            System.out.println("CARD_ID = " + card_id);
            employee.setCARD_ID(card_id);
        }
        //判断性别是否为空
//        if(sex !=null && !"".equals(sex)){
//            employee.setSex(Integer.parseInt(sex));
//        }



        //判断部门是否为空
        Dept dept = new Dept();
        if(dept_id !=null && !"".equals(dept_id)){
            dept.setId(Integer.parseInt(dept_id));
        }
        employee.setDept(dept);

        //判断职位是否为空
        //因为基本数据类型不能为0/空字符，需要转换一下
        Job job = new Job();

        if(job_id !=null && !"".equals(job_id)){
            job.setId(Integer.parseInt(job_id));
        }
        employee.setJob(job);

        //总记录数
        int count = service.getTotalEmployeeCount(employee);
        model.setTotalRecoreSum(count);
        employees = service.findAllemployees(employee, model);

        //使用数组组合
        Map<String,Object>map=new HashMap<>();
        map.put("model",model);
        map.put("employees",employees);

        //使用Gson返回
        Gson gson=new Gson();
        String json = gson.toJson(map);
        //响应到前台
        response.getWriter().write(json);

    }
}
